package com.hyd.project;

import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import org.json.JSONException;
import org.json.JSONObject;

import com.android.volley.AuthFailureError;
import com.android.volley.Request.Method;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.hyd.util.MD5Encrypt;
import com.hyd.util.isMobileUtil;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 注册界面
 * 
 * @author llf
 * 
 */
public class RegisterActivity extends Activity {
	private TextView countdown;
	private Timer timer;
	private TimerTask task;
	private Handler handler;
	private int time = 60;
	private RequestQueue queue;
	private EditText username, code, password;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_register);

		initView();
		initTimer();
	}

	private void initView() {
		queue = Volley.newRequestQueue(RegisterActivity.this);
		countdown = (TextView) findViewById(R.id.get_identifying_code);
		username = (EditText) findViewById(R.id.username);
		code = (EditText) findViewById(R.id.identifying_code);
		password = (EditText) findViewById(R.id.password);
	}

	private void initTimer() {
		timer = new Timer();
		handler = new Handler() {

			@Override
			public void handleMessage(Message msg) {
				if (time >= 0) {
					countdown.setText(time + "");
					time--;
				} else {
					task.cancel();
					countdown.setClickable(true);
					time = 60;
					countdown.setText("获取验证码");
				}
			}

		};
	}

	// 提交获取验证码的请求,用定时器进行倒计时
	public void getCode(View v) {
		StringRequest request = new StringRequest(Method.POST, getResources()
				.getString(R.string.request_head)
				+ "/api/gotAuthenticationCode",
				new Response.Listener<String>() {

					@Override
					public void onResponse(String response) {
						// 对返回结果进行解析
						try {
							JSONObject jo = new JSONObject(response);
							if (jo.getInt("resultCode") == 0) {
								// 获取验证码成功，开启倒计时的线程
								task = new TimerTask() {

									@Override
									public void run() {
										handler.sendEmptyMessage(1);
									}
								};
								timer.schedule(task, 0, 1000);
								countdown.setClickable(false);
							}
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}
				}, new Response.ErrorListener() {

					@Override
					public void onErrorResponse(VolleyError arg0) {
						Toast.makeText(RegisterActivity.this,
								getResources().getString(R.string.error),
								Toast.LENGTH_SHORT).show();
					}
				}) {

			@Override
			protected Map<String, String> getParams() throws AuthFailureError {
				Map<String, String> map = new HashMap<String, String>();
				map.put("phoneNumber", username.getText().toString());
				return map;
			}

		};
		queue.add(request);
	}

	// 注册提交
	public void Register(View v) {
		// 对填写的信息进行必要的验证
		if ("".equals(username.getText().toString())) {
			Toast.makeText(RegisterActivity.this, "手机号不能为空", Toast.LENGTH_SHORT)
					.show();
			return;
		}

		if (!isMobileUtil.isMobileNumber(username.getText().toString())) {
			Toast.makeText(RegisterActivity.this, "请填写正确的手机号码",
					Toast.LENGTH_SHORT).show();
			return;
		}

		if ("".equals(code.getText().toString())) {
			Toast.makeText(RegisterActivity.this, "验证码不能为空", Toast.LENGTH_SHORT)
					.show();
			return;
		}

		if ("".equals(password.getText().toString())) {
			Toast.makeText(RegisterActivity.this, "密码不能为空", Toast.LENGTH_SHORT)
					.show();
			return;
		}

		// 发送注册的请求
		StringRequest request = new StringRequest(Method.POST, getResources()
				.getString(R.string.request_head) + "/api/register",
				new Response.Listener<String>() {

					@Override
					public void onResponse(String response) {
						// 对返回结果进行解析
						try {
							JSONObject jo = new JSONObject(response);
							if (jo.getInt("resultCode") == 0) {
								Toast.makeText(RegisterActivity.this, "注册成功",
										Toast.LENGTH_SHORT).show();
							}
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}
				}, new Response.ErrorListener() {

					@Override
					public void onErrorResponse(VolleyError arg0) {
						Toast.makeText(RegisterActivity.this,
								getResources().getString(R.string.error),
								Toast.LENGTH_SHORT).show();
					}
				}) {

			@Override
			protected Map<String, String> getParams() throws AuthFailureError {
				Map<String, String> map = new HashMap<String, String>();
				map.put("userName", username.getText().toString());
				map.put("authenticationCode", code.getText().toString());
				map.put("password",
						MD5Encrypt.GetMD5Code(password.getText().toString()));
				System.out.println(map);
				return map;
			}

		};
		queue.add(request);
	}

	public void back(View v) {
		finish();
		overridePendingTransition(android.R.anim.slide_in_left,
				android.R.anim.slide_out_right);
	}

	@Override
	protected void onDestroy() {
		if (timer != null) {
			timer.cancel();
		}
		super.onDestroy();
	}

}
